package model

import (
	"fmt"
	"reflect"

	"gitee.com/goframe/lt-collector/libs/libce"
	"gitee.com/goframe/lt-collector/libs/orma"
	"gitee.com/goframe/lt-collector/libs/utils"
)

func BindIDModel(model orma.XTransaction) error {
	val := reflect.ValueOf(model)
	if val.Kind() != reflect.Ptr {
		panic("need a pointer for bind")
	}
	id := val.Elem().FieldByName("ID").Int()
	return libce.CacheBindModelById(model, id, func() (err error) {
		err = orma.NormalGet(model.Session().NoAutoCondition().Where("id=?", id).Get(model))
		if err == orma.ErrOrmNotFound {
			err = fmt.Errorf("%s:id:%d;记录不存在", utils.ObjectName(model), id)
		}
		return
	})
}

func deleteCacheID(model orma.XTransaction) {
	val := reflect.ValueOf(model)
	if val.Kind() != reflect.Ptr {
		panic("need a pointer for bind")
	}
	id := val.Elem().FieldByName("ID").Int()
	libce.DeleteCacheByKey(model, fmt.Sprintf("id_%d", id))
}

func ResetCacheID(model orma.XTransaction) error {
	deleteCacheID(model)
	return BindIDModel(model)
}

func checkErr(err error, methodName string) error {
	return fmt.Errorf("%s : %s", methodName, err.Error())
}
